class Solution {
public:
    /**
     * @param source: 
     * @param target: 
     * @return: return the index
     */
    int strStr(string &source, string &target) {
        int s = source.length();
        int t = target.length();
        if (s < t) return -1;
        for (int i = 0; i < s - t + 1; ++i) {
            int j;
            for (j = 0; j < t; ++j) {
                if (source[i + j] != target[j]) {
                    break;
                }
            }
            if (j == t) return i;
        }
        return -1;
    }
};

// todo:KMP

#include <iostream>
#include <vector>
#include <string>
#include <limits.h>
#include <map>
#include <cmath>
using namespace std;

int getAns(string s1, string s2) {
    int n = s1.length();
    int m = s2.length();
    vector<int> p(m);
    for (int i = 1, j = 0; i < m; ++i) {
        while(j > 0 && s2[i] != s2[j]) {
            j = p[j - 1];
        }
        if (s2[i] == s2[j]) ++j;
        p[i] = j;
    }
    for (int i = 0, j = 0; i < n; ++i) {
        while (j > 0 && s1[i] != s2[j]) {
            j = p[j - 1];
        }
        if (s1[i] == s2[j]) j++;
        if (j == m) return i - m + 1;
    }
    return -1;
}

int main() {
    string s1 = "abceddf";
    string s2 = "ddf";
    cout << getAns(s1, s2) << endl;
    return 0;
}
